package de.pa2.templates;
import java.io.File;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VelocityHelper {
	private static final Logger LOG = LoggerFactory
			.getLogger(VelocityHelper.class);
	private static VelocityEngine engine = null;
	private static String[] paths = new String[] { "" };

	private static String[] getPossiblePaths() {
		return paths;
	}

	public static String[] createFilenames(String directory, String template) {
		if ("".equals(directory)) {
			return new String[] { template + ".vm", template };
		} else if (directory.endsWith("/")) {
			return new String[] { directory + template + ".vm", template };
		} else {
			return new String[] { directory + "/" + template + ".vm", template };
		}
	}

	public static boolean hasTemplate(String template) {
		boolean result = false;
		String[] paths = getPossiblePaths();
		for (int i = 0; i < paths.length; i++) {
			String[] filenames = createFilenames(paths[i], template);
			for(String filename:filenames)
			{
				if (LOG.isDebugEnabled()) {
					LOG.debug("checking if file exists '" + filename + "'");
				}
				if (new File(filename).exists()) {
					result = true;
					break;
				}
			}
		}
		if (LOG.isDebugEnabled()) {
			LOG.debug("checking if template exists '" + template + "':"
					+ result);
		}
		return result;
	}

	private static synchronized void initEngine() throws Exception {
		if (engine != null)
			return;
		engine = new VelocityEngine();
		StringBuffer basedir = new StringBuffer();
		String[] basedirs = getPossiblePaths();
		for (int i = 0; i < basedirs.length; i++) {
			if (i > 0)
				basedir.append(",");
			basedir.append(basedirs[i]);
		}
		engine.setProperty("runtime.log.logsystem.class",
				"org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
		engine.setProperty("runtime.log.logsystem.log4j.category", "velocity");
		engine.setProperty("resource.loader", "portal");
		engine.setProperty("portal.resource.loader.class",
				VelocityResourceLoader.class.getName());
		if (LOG.isDebugEnabled())
			LOG.debug("using basedir for templates '" + basedir + "'");
		engine.setProperty("portal.resource.loader.basedir", basedir.toString());
		engine.init();
	}

	public static VelocityEngine getEngine() throws Exception {
		if (engine == null)
			initEngine();
		return engine;
	}
}
